package com.joysuch.wwyt.datadump.biz.processor;

import cn.zlg.common.datadump.annotation.DataDumpEntity;
import cn.zlg.common.datadump.processor.BaseImportEntityProcessor;
import com.joysuch.wwyt.bp.entity.contractor.BpContractor;
import com.joysuch.wwyt.bp.entity.contractor.BpContractorStaff;
import com.joysuch.wwyt.bp.entity.contractor.dsl.QBpContractor;
import com.joysuch.wwyt.bp.enums.ContractorTypeEnum;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.bp.repository.BpContractorStaffDao;
import com.joysuch.wwyt.core.entity.dsl.QBaseUser;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.datadump.biz.model.EduCertificateUserDumpBean;
import com.joysuch.wwyt.edu.entity.EduCertificateNotify;
import com.joysuch.wwyt.edu.entity.EduCertificateUser;
import com.joysuch.wwyt.edu.enums.CertStatus;
import com.joysuch.wwyt.edu.service.EduCertificateNotifyService;
import com.mysema.commons.lang.Assert;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

@Component
public class EduCertificateUserProcessor extends BaseImportEntityProcessor<EduCertificateUserDumpBean, EduCertificateUser> {

    @Autowired
    private BaseUserDao baseUserDao;

    @Autowired
    private BpContractorStaffDao bpContractorStaffDao;
    @Autowired
    private JPAQueryFactory queryFactory;

    @Autowired
    private EduCertificateNotifyService eduCertificateNotifyService;

    @Override
    public EduCertificateUser processBeforePersist(EduCertificateUserDumpBean origin, EduCertificateUser entity, DataDumpEntity annotation, boolean override) {
        if("是".equals(origin.getUserContractorFlag())) {
            entity.setUserContractorFlag(1);
            BpContractorStaff user = bpContractorStaffDao.findByCodeANDAndState(origin.getUserCode());
            Assert.notNull(user, String.format("承包商人员: %s, 编号 %s 不存在 ", origin.getUserName(), origin.getUserCode()));
            validateContractorType(user.getContractorId());
            entity.setUserId(user.getId());
        } else {
            entity.setUserContractorFlag(0);
            Long id = queryFactory.select(QBaseUser.baseUser.id).from(QBaseUser.baseUser).where(QBaseUser.baseUser.code.eq(origin.getUserCode())
                    .and(QBaseUser.baseUser.state.eq(1).or(QBaseUser.baseUser.state.isNull()))).fetchFirst();
            Assert.notNull(id, String.format("系统人员: %s, 编号 %s 不存在 ", origin.getUserName(), origin.getUserCode()));
            entity.setUserId(id);
        }
        Integer aheadDays=0;
        EduCertificateNotify notify = eduCertificateNotifyService.findByCertId(entity.getCertId());
        if (notify!=null){
            aheadDays=notify.getAheadDays();
        }
        //if (entity.getOutOfDateTime() != null) {
        //    //即将过期
        //
        //    if ((entity.getOutOfDateTime().after(new Date())||
        //            com.joysuch.wwyt.util.DateUtils.getStartOfDay(entity.getOutOfDateTime()).equals(com.joysuch.wwyt.util.DateUtils.getStartOfDay(new Date())))
        //            && entity.getOutOfDateTime().before(DateUtils.addDays(new Date(), aheadDays))) {
        //        entity.setCertStatus(CertStatus.EXPIRING_SOON.status.toString());
        //    } else if (entity.getOutOfDateTime().after(new Date()) &&(entity.getTakenTime()==null||entity.getTakenTime().before(new Date())) ) {
        //        //有效
        //        entity.setCertStatus(CertStatus.EFFECTIVE.status.toString());
        //    }  else if (entity.getOutOfDateTime().before(new Date())) {
        //        //过期
        //        entity.setCertStatus(CertStatus.EXPIRED.status.toString());
        //    } else {
        //        entity.setCertStatus(CertStatus.NO_EFFECTIVE.status.toString());
        //    }
        //} else {
        //    entity.setCertStatus(CertStatus.NO_EFFECTIVE.status.toString());
        //}
        entity.setCertStatus(getEduCertStatus(entity.getTakenTime(), entity.getOutOfDateTime(), aheadDays).status.toString());
        entity.setCertificateStatus(1);
//        entity.setCertId(findCertId(origin.getCertTypeName()));
        return entity;
    }

    private void validateContractorType(Long contractorId) {
        QBpContractor q = QBpContractor.bpContractor;
        BpContractor contractor = queryFactory.select(q).from(q).where(q.id.eq(contractorId), q.state.eq(DataStateTypes.EFFECTIVE.getState()).or(q.state.isNull())).fetchFirst();
        Assert.notNull(contractor, "该人员对应的承包商不存在 ");
        Assert.isTrue(ContractorTypeEnum.QUALIFIED.getDesc().equals(contractor.getContractorType()), "不是合格承包商，不能导入 ");
    }

//    private Long findCertId(String certTypeName) {
//        QEduCertificate q = QEduCertificate.eduCertificate;
//        QEdu
//        queryFactory.select(q.id).from(q,)
//    }

    /**
     * 处理证书状态
     *
     * @param startDate 有效期开始日期
     * @param endDate   有效期结束日期
     * @param remindDays 提醒天数
     * @return {@link CertStatus} 证书状态
     */
    private CertStatus getEduCertStatus(Date startDate, Date endDate, Integer remindDays) {
        // 未录入证书时间， 默认长期有效
        if (Objects.isNull(startDate) && Objects.isNull(endDate)) {
            return CertStatus.EFFECTIVE;
        }

        // 当前日期
        Date nowDate = new Date();

        // 待生效
        if (Objects.nonNull(startDate) && (startDate.after(nowDate))) {
            return CertStatus.NO_EFFECTIVE;
        }

        // 即将失效:根据提醒天数判断是否即将失效
        if (Objects.nonNull(endDate) && ((endDate.after(new Date())||
                com.joysuch.wwyt.util.DateUtils.getStartOfDay(endDate).equals(com.joysuch.wwyt.util.DateUtils.getStartOfDay(new Date())))
                && endDate.before(DateUtils.addDays(new Date(), remindDays)))) {

            return CertStatus.EXPIRING_SOON;
        }

        // 失效
        if (Objects.nonNull(endDate) && endDate.before(nowDate)) {
            return CertStatus.EXPIRED;
        }

        return CertStatus.EFFECTIVE;
    }
}
